package thread;

public class SynchronizedLockDemo {
    private static int count = 0;

    public static void main(String[] args) throws InterruptedException {
        // 测试线程不安全的情况
        System.out.println("线程不安全示例结果：");
        testThreadUnsafe();

        // 重置计数器
        count = 0;

        // 测试线程安全的情况
        System.out.println("线程安全示例结果：");
        testThreadSafe();


    }

    // 线程不安全：没有锁
    public static void testThreadUnsafe() throws InterruptedException {
        Thread[] threads = new Thread[10];
        for (int i = 0; i < 10; i++) {
            threads[i] = new Thread(() -> {
                for (int j = 0; j < 1000; j++) {
                    increment();
                    decrement();
                }
            });
        }

        // 启动所有线程
        for (Thread thread : threads) {
            thread.start();
        }

        // 等待所有线程完成
        for (Thread thread : threads) {
            thread.join();
        }

        System.out.println("最终计数器值（非线程安全）: " + count);
    }

    // 线程安全：内部已经有同步机制（synchronizedIncrement和synchronizedDecrement方法）
    public static void testThreadSafe() throws InterruptedException {
        Thread[] threads = new Thread[10];
        for (int i = 0; i < 10; i++) {
            threads[i] = new Thread(() -> {
                for (int j = 0; j < 1000; j++) {
                    synchronizedIncrement();
                    synchronizedDecrement();
                }
            });
        }

        // 启动所有线程
        for (Thread thread : threads) {
            thread.start();
        }

        // 等待所有线程完成
        for (Thread thread : threads) {
            thread.join();
        }

        System.out.println("最终计数器值（线程安全）: " + count);

    }

    // 模拟线程不安全的增加计数器
    private static void increment() {
        count++;
    }

    // 模拟线程不安全的减少计数器
    private static void decrement() {
        count--;
    }

    // 线程安全的增加计数器
    private synchronized static void synchronizedIncrement() {
        count++;
    }

    // 线程安全的减少计数器
    private synchronized static void synchronizedDecrement() {
        count--;
    }
}